﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace MonitorAgent
{
   class TCPServer
   {
      private TcpListener tcpListener;
      private Thread listenThread;
      private int m_port;

      public TCPServer(int port)
      {
         m_port = port;

         this.tcpListener = new TcpListener(IPAddress.Any, m_port);
         this.listenThread = new Thread(new ThreadStart(ListenForClients));
         this.listenThread.Start();
      }

      private void ListenForClients()
      {
         this.tcpListener.Start();

         while (true)
         {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();
            Socket socket = this.tcpListener.AcceptSocket();
            //create a thread to handle communication 
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
         }
      }


      private void HandleClientComm(object client)
      {
         Socket clientSocket = (Socket)client;
         //NetworkStream clientStream = tcpClient.GetStream();

         byte[] message = new byte[4096];
         int bytesRead;


         try
         {
            clientSocket.Receive(message);

            // handle message

            // Gather Data

            // send data
            clientSocket.Send(Encoding.UTF8.GetBytes("This is a test"));
         }
         catch (Exception e)
         {
            //a socket error has occured
            System.Diagnostics.Trace.WriteLine("ERROR: " + e.Message);
         }
         finally
         {
            clientSocket.Close();
         }

      }

   }
}
